<?php
namespace haibao\jiepai\data;

use haibao\cms\business\control\PublicController;
use haibao\classlibrary\jiepai\Config;

class User extends \haibao\jiepai\data\BaseMysql
{

    public function __construct()
    {
        parent::__construct('\haibao\jiepai\model\data\user\CmsAdminUsers');
    }

    public function saveManageUser($option)
    {
        if ($option['checkType'] == 1) {
            $this->query('update cms_user_punish_statistic set PunishTypeNum1=PunishTypeNum1+1');
        } else if ($option['checkType'] == 2) {
            $this->query('update cms_user_punish_statistic set PunishTypeNum2=PunishTypeNum2+1');
        } else if ($option['checkType'] == 3) {
            $this->query('update cms_user_punish_statistic set PunishTypeNum3=PunishTypeNum3+1');
        } else if ($option['checkType'] == 4) {
            $this->query('update cms_user_punish_statistic set PunishTypeNum4=PunishTypeNum4+1');
        }


        $sql = "INSERT INTO cms_user_manage_log (Type,Reason,UserID,AdminUserID,EndTime) values (%s,%s,%s,%s,%s)";
        $nowTime = new \DateTime();
        $page = 1;
        $nowTime = $nowTime->format("Y-m-d H:i:s");
        if ($option['delComment']) {
            $this->query("UPDATE cms_comment SET AuditStatus=2 WHERE Flag=0 AND UserID=" . $option['userId'] . "");
            $this->query("UPDATE cms_comment_reply SET AuditStatus=2 AND Flag=0 AND UserID=" . $option['userId'] . "");
        }
        $this->query($sql, array($option['checkType'], $option['replyContent'], $option['userId'], $option['auditUser'], $option['endTime'] ? $option['endTime'] : null));

    }

    public function insertUserTitle($userId, $userTitle)
    {
        $title = '';
        if ($userTitle == 0) {
            $title = null;
        } elseif ($userTitle == 1) {
            $title = '(P)';
        } elseif ($userTitle == 2) {
            $title = '(OP)';
        } elseif ($userTitle == 3) {
            $title = '(P)(OP)';
        }

        $this->query('update cms_users set Title=%s where UserId = %s', array($title, $userId));
    }

    public function getUserList($option = array())
    {
        $select = 'SELECT u.*,f.ServerFileName as Avatar ';
        $sql = ' FROM cms_users u LEFT JOIN cms_files f ON u.AvatarID=f.FileID where 1=1 ';
        $userList = array('list' => array(), 'cnt' => 0);
        $page = 1;

        if (isset($option['manageType'])) {
            $sql .= ' and u.Status=' . $option['manageType'] . ' ';
        }
        if (isset($option['userInfo']) && $option['userInfo']) {
            $sql .= ' and u.UserID=' . $option['userInfo'] . ' ';
        }
        if (isset($option['headLine']) && $option['headLine']) {

            if ($option['headLine'] == 1) {
                $sql .= ' and u.Title like "%(P)%"';
            } elseif ($option['headLine'] == 2) {
                $sql .= ' and u.Title like "%(OP)%"';
            }

        }

        if (isset($option['startDate']) && $option['startDate'] && isset($option['endDate']) && $option['endDate']) {
            $sql .= ' and u.CreateTime between "' . $option['startDate'] . '" and "' . $option['endDate'] . '" ';
        }


        if ($option) {
            $page = isset($option['page']) ? $option['page'] : 1;
        }


        $sql .= '  ORDER BY u.CreateTime desc ';

        $result = $this->query($select . $sql . ' limit ' . (($page - 1) * 10 . ' , 10 '));


        while ($row = $result->fetch_assoc()) {
            array_push($userList['list'], $row);
        }
        if ($page == 1) {
            $sql = 'select count(*) as cnt ' . $sql . ' ';
            $userList = array_merge($userList, $this->query($sql)->fetch_assoc());
        }
        return $userList;

    }

    public function getUserManageList($option = array())
    {
        $nowTime = new \DateTime();
        $page = 1;
        $nowTime = $nowTime->format("Y-m-d H:i:s");

        $manageList = array('list' => array(), 'cnt' => 0);

        $select = 'SELECT *,s.UserID,(UnPassTypeNum1+UnPassTypeNum2+UnPassTypeNum3+UnPassTypeNum4+UnPassTypeNum5+UnPassTypeNum6) as UnPassNum,u.NickName,f.ServerFileName AS Avatar,l.CreateTime ';
        $sql = 'FROM cms_user_punish_statistic s LEFT JOIN cms_user_manage_log l ON l.ID=( ' .
            'SELECT ID FROM cms_user_manage_log WHERE UserID=s.UserID ORDER BY CreateTime DESC LIMIT 1) ' .
            'LEFT JOIN cms_users u ON s.UserID=u.UserID LEFT JOIN cms_files f ON u.AvatarID=f.FileID ' .
            'where 1=1 ';
        if (isset($option['manageType']) && $option['manageType']) {
            switch ($option['manageType']) {
                case 'canSolve':
                    $sql .= ' and (l.Type!=4 or l.Type is null) and (l.Type!=3 or l.Type is null or l.EndTime<"' . $nowTime . '") ';
                    break;
                case 'silence':
                    $sql .= ' and l.Type=3 and l.EndTime>"' . $nowTime . '" ';
                    break;
                case 'freeze':
                    $sql .= ' and l.Type=4 ';
                    break;
            }
        }

        if ($option) {
            $page = isset($option['page']) ? $option['page'] : 1;
        }

        if (isset($option['userInfo']) && $option['userInfo']) {
            $sql .= ' and s.UserID=' . $option['userInfo'];
        }
        if (isset($option['exceptionType']) && $option['exceptionType']) {
            $sql .= ' and s.' . $option['exceptionType'] . '>0 ';
        }

        $sql .= ' ORDER BY l.CreateTime DESC ';


        $result = $this->query($select . $sql . ' limit ' . (($page - 1) * 10 . ' , 10 '));

        while ($row = $result->fetch_assoc()) {
            array_push($manageList['list'], $row);
        }

        if ($page == 1) {
            $sql = 'select count(*) as cnt ' . $sql . '';
            $manageList = array_merge($manageList, $this->query($sql)->fetch_assoc());
        }
        return $manageList;
    }

    public function getExaminedReports($option = array())
    {

        $reportList = array('list' => array(), 'cnt' => 0);
//         $sql = 'SELECT v.*,u.NickName,COUNT(r.ID) AS count,MIN(r.CreateTime) as startTime,MAX(r.CreateTime) as endTime FROM cms_reports r ' .
//             'LEFT JOIN ( ' .
//             'SELECT CommentID as ID,Content,AuditStatus,UserID,1 as Type FROM cms_comment ' .
//             'UNION ALL ' .
//             'SELECT ReplyID as ID,Content,AuditStatus,UserID,2 as Type FROM cms_comment_reply ' .
//             ') v ON r.TypeID=v.ID AND r.Type=v.Type ' .
//             'LEFT JOIN cms_users u ON v.UserID=u.UserID ' .
//             'WHERE v.AuditStatus=0 GROUP BY v.ID,v.Type ';

        $sql = 'SELECT cc.CommentID as ID,cc.Content,cc.AuditStatus,cc.UserID,
            cr.ReplyID,cr.Content as ReplyContent,cr.AuditStatus as ReplyAuditStatus,cr.UserID as ReplyUserID,
            u.NickName,r.Type,COUNT(r.ID) AS count,MIN(r.CreateTime) as startTime,MAX(r.CreateTime) as endTime FROM cms_reports r 
            LEFT JOIN cms_comment cc ON cc.CommentID = r.TypeID and cc.AuditStatus=0 
            LEFT JOIN cms_comment_reply cr ON cr.ReplyID = r.TypeID and cr.AuditStatus=0 
            LEFT JOIN cms_users u ON cc.UserID=u.UserID and cr.UserID=u.UserID 
            GROUP BY ID,r.Type ';
        if ($option) {
            $page = isset($option['page']) ? $option['page'] : 1;
        }
        $result = $this->query($sql . ' ORDER BY  endTime desc   limit ' . ($page - 1) * $option['pageSize'] . ',' . $option['pageSize']);

        while ($row = $result->fetch_assoc()) {
            array_push($reportList['list'], $row);
        }
        if ($page == 1) {
            $sql = 'select count(*) as cnt from (' . $sql . ') t';
            $reportList = array_merge($reportList, $this->query($sql)->fetch_assoc());
        }
        return $reportList;

    }

    public function getReportContextUsers($commentId, $commentType)
    {

        $sql = 'SELECT r.UserID,u.NickName FROM cms_reports r LEFT JOIN cms_users u ON r.UserID=u.UserID WHERE r.Type=%s AND r.TypeID=%s';
        $result = $this->query($sql, array((int)$commentType, (int)$commentId));
        $list = array();
        while ($row = $result->fetch_assoc()) {
            array_push($list, $row);
        }
        return $list;
    }


    public function getUserFeedbacks($option)
    {

        $adviceList = array('list' => array(), 'cnt' => 0);
        $select = 'SELECT u.NickName,a.UserID,f.ServerFileName as Avatar,a.*,t.Content as ReplyContent,t.ReplyID ';
        $count = 'select count(*) as cnt ';

        $sql = ' FROM cms_advice a  ' .
            'LEFT JOIN cms_users u ON a.UserID=u.UserID LEFT JOIN cms_files f ON u.AvatarID=f.FileID  ' .
            'LEFT JOIN cms_advice_reply t ON t.ReplyID=(SELECT r.ReplyID FROM cms_advice_reply r WHERE r.AdviceID = a.AdviceID and r.Flag=0  ORDER BY r.ReplyTime desc limit 1)  ' .
            'where 1=1';

        switch ($option['type']) {
            case 'all':
                $sql .= ' and a.Flag=0';
                break;
            case 'solved':
                $sql .= ' and a.Flag=0 and a.Status=1';
                break;
            case 'unsolved':
                $sql .= ' and a.Flag=0 and a.Status=0';
                break;
            default :
                $sql .= ' and a.Flag=0';
        }
        if (isset($option['status']) && $option['status'] !== '') {
            $sql .= ' and a.`Status`=' . $option['status'];
        }
        if (isset($option['userId']) && $option['userId']) {
            $sql .= ' and a.UserID=' . $option['userId'];
        }

        if (isset($option['keyword']) && $option['keyword']) {
            $sql .= ' and (a.AdviceID=' . (Number($option['keyword']) || -1) . ' or a.Content like "%' . $option['keyword'] . '%" or t.Content like "%' . $option['keyword'] . '%")';
        }

        //时间
        if ((isset($option['start']) && $option['start']) && (isset($option['end']) && $option['end'])) {
            $sql .= ' and a.CreateTime between "' . $option['start'] . '" and "' . $option['end'] . '"';
        }

        if (isset($option['adviceType']) && $option['adviceType']) {
            $sql .= ' and a.Type=' . $option['adviceType'];
        }

        if (isset($option['osType']) && $option['osType']) {
            $sql .= ' and a.ClientPhoneOSType=' . $option['osType'];
        }

        if (isset($option['appVersion']) && $option['appVersion']) {
            $sql .= ' and a.AppVersion="' . $option['appVersion'] . '"';
        }

        $result = $this->query($select . $sql . ' ORDER BY CreateTime DESC limit ' . ($option['page'] - 1) * $option['pageSize'] . ',' . $option['pageSize']);

        while ($row = $result->fetch_assoc()) {
            array_push($adviceList['list'], $row);
        }

        if ($option['page'] == 1) {
            $sql = $count . $sql;
            $adviceList = array_merge($adviceList, $this->query($sql)->fetch_assoc());
        }
        return $adviceList;
    }

    public function getFeedbackPictures($typeId, $type)
    {

        $sql = 'SELECT p.PictureID FROM cms_advice_pictures p where p.TypeID=%s and p.Type=%s';

        $result = $this->query($sql, array((int)$typeId, (int)$type));

        $list = array();
        while ($row = $result->fetch_assoc()) {
            array_push($list, $row);
        }
        return \haibao\jiepai\data\BaseMysql::mergeDataAndImage($list, 'PictureID');

    }

    /* 获取反馈列表 */
    public function getAdviceList($userId, $adviceId)
    {
        $param = array($userId);
        $sql = 'SELECT AdviceID,UserID,Content,CreateTime,Status FROM cms_advice WHERE Flag = 0 AND UserID = %s';
        if ($adviceId != 0) {
            $sql .= ' AND AdviceId < %s';
            $param[] = $adviceId;
        }
        $sql .= ' ORDER BY CreateTime desc LIMIT ' . (intval(Config::getConfig(Config::LARGE_ARTICLE_PAGE_SIZE)) + 1);

        $result = $this->query($sql, $param);

        $list = array();
        while ($row = $result->fetch_assoc()) {
            array_push($list, $row);
        }

        return $list;
    }

    /**
     * @param \haibao\jiepai\model\data\advice\CmsAdvice $model
     * @param array $picIds
     * @return mixed
     */
    public function addAdvice($model, $picIds)
    {
        //添加反馈
        $this->add($model);
        $adviceId = $model->Id;

        //插入图片
        if (!empty($picIds)) {
            $this->addImage($picIds, $adviceId, \haibao\jiepai\model\data\user\CmsAdvicePictures::IS_ADVICE);
        }

        return $adviceId;
    }

    /**
     * @param \haibao\jiepai\model\data\user\CmsAdviceReply $model
     * @param array $picIds
     * @return mixed
     */
    public function addUserAdviceReply($model, $picIds)
    {
        $this->add($model);
        $replayId = $model->Id;

        //插入图片
        if (!empty($picIds)) {
            $this->addImage($picIds, $replayId);
        }

        return $replayId;
    }

    public function fixAdvice($adviceId, $userId)
    {
        $sql = 'UPDATE cms_advice SET Status=1 where AdviceID=%s AND UserID = %s';
        $this->query($sql, array($adviceId, $userId));
    }

    public function addAdviceReply($optionData)
    {

        $sql = 'insert into cms_advice_reply (`UserID`,`ReplyTime`,`Content`,`AdviceID`,`Type`,`Status`) values (%s,%s,%s,%s,%s,%s)';
        $this->query($sql, $optionData);

    }

    public function getFeedback($adviceId)
    {

        $sql = 'SELECT *,AdviceID as ID,CreateTime as Time FROM cms_advice WHERE AdviceID=%s';
        return $this->query($sql, array((int)$adviceId))->fetch_assoc();
    }

    public function getFeedbackReply($adviceId)
    {
        $sql = 'SELECT r.ReplyID as ID,r.Type as ReplyType,r.Content,r.Status,r.ReplyTime as Time,r.UserID,u.NickName,r.UserID as AdminID FROM cms_advice_reply r ' .
            'LEFT JOIN cms_admin u ON r.UserID=u.AdminID  WHERE r.AdviceID=%s and r.Flag=0';
        $result = $this->query($sql, array((int)$adviceId));

        $userIds = array();
        $list = array();
        while ($row = $result->fetch_assoc()) {
            array_push($list, $row);
            $userIds[] = $row['UserID'];
            if ($row['Status'] == 0 && isset($row['ID']) && $row['ID']) {
                $this->query('update cms_advice_reply set Status=1 where ReplyID=%s', array(
                    $row['ID']
                ));
            }
        }

        if ($userIds) {
            $cmsUserData = new \haibao\cms\data\User();
            $userList = $cmsUserData->getUserInfoByIds($userIds);
            foreach ($list as $k => $value) {
                if (!empty($userList) && !empty($userList[$value['UserID']])) {
                    $value['NickName'] = $userList[$value['UserID']]['RealName'];
                    $list[$k] = $value;
                }
            }
        }


        return $list;
    }

    public function updateAdviceStatus($adviceId, $status)
    {

        $sql = 'update cms_advice set Status=%s where AdviceID=%s';
        $this->query($sql, array($status, $adviceId));
    }

    public function closeAdviceReply($replyId)
    {

        $sql = 'update cms_advice_reply set Flag=-1 where ReplyID=%s';
        $this->query($sql, array($replyId));
    }

    /**
     * @param \haibao\jiepai\model\data\user\CmsUsers $userModel
     * @return array|null|string
     */
    public function userLogin($userModel)
    {
        $userArr = array();
        if ($userModel->Id) {
            switch ($userModel->RegisterType) {
                case 2:
                    $userModel->RegisterType = '微信';
                    break;
                case 3:
                    $userModel->RegisterType = 'QQ';
                    break;
                case 4:
                    $userModel->RegisterType = '微博';
                    break;
                default:
                    $userModel->RegisterType = '官方';
                    break;
            }
            $userModel->Message = '你已于' . date("Y-m-d H:i") . '在其他设备(' . $userModel->DeviceName . ')上进行登录';
            $userModel->Sid = $this->getUuid();

            $isFirstLogin = false;
            $sql = 'SELECT UserID,NickName,Title,Sid FROM `cms_users` WHERE UserID = %s  limit 1';
            $result = $this->query($sql, array($userModel->Id))->fetch_assoc();
            if ($result && $result['UserID']) {
                //修改用户表
                $arrSet = array(
                    'Sid' => $userModel->Sid,
                    'LastLoginDevice' => $userModel->LastLoginDevice,
                    'LastLoginSid' => $result['Sid'],
                    'Message' => $userModel->Message,
                    'RegisterType' => $userModel->RegisterType
                );
                $this->updateUser($userModel->Id, $arrSet);
                $result['IsFirstLogin'] = $isFirstLogin;
                $result['Sid'] = $userModel->Sid;
                return $result;
            } else {
                $userModel->CreateTime = new \DateTime();
                $this->add($userModel);
                //创建一个默认相册
                $albumModel = new \haibao\jiepai\model\data\user\CmsUserAlbums();
                $albumModel->UserID = $userModel->Id;
                $albumModel->AlbumName = '默认相册';
                $albumModel->Type = $albumModel::ALBUM_DEFAULT;
                $albumModel->CreateTime = new \DateTime();
                $albumModel->Flag = $albumModel::FLAG_IS;
                $this->add($albumModel);

                $isFirstLogin = true;
                //第一次登录，更新消息表
                $sql = 'SELECT ID FROM cms_messages_manage WHERE Category=3 limit 1';
                $result = $this->query($sql)->fetch_assoc();
                if ($result) {
                    $sql = 'INSERT INTO cms_messages (TypeID,UserID,Type) VALUES (%s,%s,%s)';
                    $this->query($sql, array($result['ID'], $userModel->Id, 5));
                }
                $userArr = $userModel->toArray();
                $userArr['IsFirstLogin'] = $isFirstLogin;
                return $userArr;
            }
        }
    }

    public function userLogout($userId)
    {
        $sql = 'UPDATE cms_users SET Sid=null where UserID=%s';
        $this->query($sql, array($userId));
    }

    public function CheckUserStatus($userId)
    {
        $sql = 'SELECT Type,EndTime from cms_user_manage_log WHERE UserID= %s ORDER BY ID desc limit 1';
        return $this->query($sql, array($userId))->fetch_assoc();
    }

    public function updateUser($userId, $arrSet)
    {
        $param = array();
        $setStr = '';
        foreach ($arrSet as $key => $val) {
            $setStr .= ',' . $key . '=%s';
            $param[] = $val;
        }

        if ($setStr) {
            $sql = 'UPDATE cms_users SET ' . ltrim($setStr, ',') . ' where UserID=%s';
            $param[] = $userId;
            $this->query($sql, $param);
        }
    }

    public function getUserInfo($sid)
    {
        if (!$sid) {
            return false;
        }
        $sql = 'SELECT UserID,NickName from cms_users where Sid=%s limit 1';
        $userInfo = $this->query($sql, array($sid))->fetch_assoc();

        if ($userInfo && $userInfo['UserID']) {
            $manageLogsql = 'SELECT `Type`,EndTime from cms_user_manage_log WHERE UserID=%s ORDER BY CreateTime desc limit 1';
            $userLog = $this->query($manageLogsql, array($userInfo['UserID']))->fetch_assoc();
            if ($userLog) {
                $userInfo['Type'] = $userLog['Type'];
                $userInfo['EndTime'] = $userLog['EndTime'];
            }
        } else {
            $lastLoginSidSql = 'SELECT Message from cms_users WHERE LastLoginSid=%s limit 1';
            $lastLogin = $this->query($lastLoginSidSql, array($sid))->fetch_assoc();
            if ($lastLogin && $lastLogin['Message']) {
                return array(
                    'Type' => 'kickoff',
                    'Message' => $lastLogin['Message']
                );
            } else {
                return false;
            }
        }
        return $userInfo;
    }

    // 1->文章点赞，2->文章收藏，3->评论点赞，4->关注达人,5->回复点赞
    public function getUserActions($type, $articleIds, $userId)
    {
        $articleIds = is_array($articleIds) ? $articleIds : array($articleIds);
        $dataList = array();
        if ($type && $articleIds && $userId) {
            $str = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
            $sql = 'SELECT ID,TypeID FROM cms_user_action WHERE Flag = 0 AND Type=' . $type . ' AND TypeID IN (' . $str . ') AND UserID=' . $userId;
            $result = $this->query($sql, $articleIds);
            while ($row = $result->fetch_assoc()) {
                $dataList[$row['TypeID']] = $row['TypeID'];
            }
        }
        return $dataList;
    }

    public function insertUserActions($type, $articleIds, $userId)
    {
        $articleIdArr = explode(",", $articleIds);
        $sql = 'SELECT * from cms_user_action where TypeID IN (' . $articleIds . ') AND Type=' . $type . ' AND Flag = 0 AND UserID =' . $userId;
        $exitData = $this->query($sql);

        $exitArticleId = array();
        while ($exitData->fetch_assoc()) {
            array_push($exitArticleId, $exitData->getData('TypeID'));
        }
        $endIds = array_diff($articleIdArr, $exitArticleId);
        $resultCount = 0;
        if (count($endIds) > 0) {
            foreach ($endIds as $k => $v) {
                $sql = 'INSERT INTO cms_user_action (Type,TypeID,UserID) VALUES (%s,%s,%s)';
                $result = $this->query($sql, array($type, $v, $userId));
            }
            $resultCount = $result->getAffectRow();
        }
        return $resultCount;
    }

    /* 更新用户行为 */
    public function updateUserActions($flag, $type, $articleId, $userId)
    {
        $sql = "UPDATE cms_user_action SET Flag=" . $flag . " WHERE Flag = 0 AND TypeID = " . $articleId . "  AND UserID = " . $userId . " AND Type=" . $type;
        $result = $this->query($sql);
        return $result->getAffectRow();
    }

    public function cancelCollectArticles($type, $articleIds, $userId)
    {
        $sql = "UPDATE cms_user_action SET Flag = -1 WHERE Flag = 0 AND TypeID IN (" . $articleIds . ') AND UserID = ' . $userId . ' AND Type=' . $type;
        return $this->query($sql)->getAffectRow();
    }

    public function replaceVisitorToUser($deviceId, $userId)
    {
        $sql = 'SELECT count(*) as count from cms_jury_action WHERE Flag=0 AND Type=1 AND TypeID=%s';
        $result = $this->query($sql, array($userId))->fetch_assoc();
        if ($result && $result['count'] > 0) {
            $sql = 'SELECT VisitorID FROM cms_visitors WHERE DeviceID=%s AND Flag=0 ORDER BY CreateTime desc LIMIT 1';
            $result = $this->query($sql, array($deviceId))->fetch_assoc();
            if ($result) {
                $sql = 'UPDATE cms_jury_action SET Type=1,TypeID=%s WHERE Flag=0 AND Type=2 AND TypeID=%s';
                $this->query($sql, array($userId, $result['VisitorID']));
            }
        }
    }

    public function getUserSubscribeOldDate($userId)
    {
        $cache = new \haibao\jiepai\cache\User();
        return $cache->getUserSubscribeOldDate($userId);
    }

    public function checkSubscribeTagHaveNew($tagId, $lastDataTime = null, $isCelebrity = false)
    {
        $dataList = array('haveNew' => 0, 'time' => 0);
        $sql = 'SELECT count(*) as count,MAX(a.PublishTime) as time FROM cms_articles a LEFT JOIN cms_article_tags t ON a.ArticleID=t.ArticleID 
                WHERE a.Flag=0 AND a.PublishStatus=1 AND t.TagID=%s ';
        if ($isCelebrity) {
            $sql = 'SELECT count(*) as count,MAX(a.PublishTime) as time FROM cms_articles a LEFT JOIN cms_article_celebrity t ON a.ArticleID=t.ArticleID 
                WHERE a.Flag=0 AND a.PublishStatus=1 AND t.CelebrityID=%s ';
        }
        if (!empty($lastDataTime)) {
            $sql .= 'AND a.PublishTime>"' . $lastDataTime . '"';
        }
        $result = $this->query($sql, array($tagId));
        while ($row = $result->fetch_assoc()) {
            if ($row['count'] > 1) {
                $dataList = array('haveNew' => 1, 'time' => date('Y-m-d H:i:s', strtotime($row['time'])));
                break;
            } else {
                $sqlStr = 'SELECT MAX(a.PublishTime) as time FROM cms_articles a LEFT JOIN cms_article_tags t ON a.ArticleID=t.ArticleID
                          WHERE a.Flag=0 AND a.PublishStatus=1 AND t.TagID=%s';
                if ($isCelebrity) {
                    $sqlStr = 'SELECT MAX(a.PublishTime) as time FROM cms_articles a LEFT JOIN cms_article_celebrity t ON a.ArticleID=t.ArticleID
                          WHERE a.Flag=0 AND a.PublishStatus=1 AND t.CelebrityID=%s';
                }
                if (!empty($lastDataTime)) {
                    $sqlStr .= 'AND a.PublishTime<"' . $lastDataTime . '"';
                }
                $resultData = $this->query($sqlStr, array($tagId));
                while ($rowData = $resultData->fetch_assoc()) {
                    $dataList = array('haveNew' => 0, 'time' => date('Y-m-d H:i:s', strtotime($row['time'])));
                    break;
                }
            }
        }

        return $dataList;
    }

    private function addImage($picIds, $objectId, $isReply = \haibao\jiepai\model\data\user\CmsAdvicePictures::IS_REPLY)
    {
        $advicePicModels = array();
        $picIds = explode(',', $picIds);
        foreach ($picIds as $k => $id) {
            $advicePicModel = new \haibao\jiepai\model\data\user\CmsAdvicePictures();
            $advicePicModel->Index = $k;
            $advicePicModel->PictureID = $id;
            $advicePicModel->Flag = 0;
            $advicePicModel->Type = $isReply;
            $advicePicModel->TypeID = $objectId;

            $advicePicModels[] = $advicePicModel;
        }

        if ($advicePicModels) {
            $this->addAll($advicePicModels);
        }
    }

    private function getUuid()
    {
        $chars = md5(uniqid(time(), true));
        $uuid = substr($chars, 0, 8) . '-';
        $uuid .= substr($chars, 8, 4) . '-';
        $uuid .= substr($chars, 12, 4) . '-';
        $uuid .= substr($chars, 16, 4) . '-';
        $uuid .= substr($chars, 20, 12);
        return $uuid;
    }

    public function getUserSubscribeOptions($userId)
    {
        $option = array();
        $option['fashionistas'] = array();
        $option['tags'] = array();
        $option['tagColumns'] = array();
        $option['columns'] = array();
        $sql = 'SELECT a.*,c.TagID FROM cms_user_action a LEFT JOIN cms_columns c ON a.TypeID=c.ColumnID AND a.Type=6 ' .
            'WHERE a.UserID=%s AND a.Flag=0 AND a.Type IN(4,6,7)';
        $result = $this->query($sql, array($userId));
        while ($row = $result->fetch_assoc()) {
            switch ($row['Type']) {
                case 4:
                    array_push($option['fashionistas'], $row['TypeID']);
                    break;
                case 7:
                    array_push($option['tags'], $row['TypeID']);
                    break;
                case 6:
                    if ($row['TagID']) {
                        array_push($option['tagColumns'], $row['TypeID']);
                        break;
                    } else {
                        array_push($option['columns'], $row['TypeID']);
                        break;
                    }
            }

        }
        return $option;
    }

    public function checkSubscribeHaveNew($option, $userDataCache)
    {
        $unRedNum = 0;
        $celebrityIds = array();
        if ($option['fashionistas']) {
            $celebrityIds = $option['fashionistas'];
        }

        if ($celebrityIds) {
            $sql = 'SELECT count(*) as count FROM cms_articles a LEFT JOIN cms_article_celebrity t ON a.ArticleID=t.ArticleID ' .
                'WHERE a.Flag=0 AND a.PublishStatus=1 AND a.PublishTime < NOW() AND a.PublishTime>"' . $userDataCache . '" and t.CelebrityID in(' . implode(',', $celebrityIds) . ')';
            $result = $this->query($sql);
            while ($row = $result->fetch_assoc()) {
                $unRedNum = $row['count'];
            }
        } else {
            /*
             $tags = $columns = array();
             if($option['tagColumns']){
                $tags = $option['tagColumns'];
            }
            if($option['columns']){
                $columns = $option['columns'];
            }
            $endSql = '';
            if (count($tags) > 0) $endSql .= ' or t.TagID in(' + implode(',',$tags) + ') ';
            if (count($columns) > 0) $endSql .= ' or a.ColumnID in(' + implode(',',$columns) + ') ';
            $endSql = str_replace('or', '', $endSql);
            if ($endSql) {
                $sql = 'SELECT count(*) as count FROM cms_articles a LEFT JOIN cms_article_tags t ON a.ArticleID=t.ArticleID ' .
                    'WHERE a.Flag=0 AND a.PublishStatus=1 AND a.PublishTime < NOW() AND a.PublishTime>"' . $userDataCache . '" and (' . $endSql . ') ';
                $result = $this->query($sql);
                while ($row = $result->fetch_assoc()){
                    $unRedNum = $row['count'];
                }
            }*/
        }
        return $unRedNum;
    }

    public function getUserSubscribes($tagIds, $columnsId = array(), $celebrityIds = array(), $lastTime = 0, $limit = 30)
    {
        $list = array();
        if ($celebrityIds) {
            $sql = 'SELECT a.ArticleID, c.ID AS ContentID,c.ContentInfo as FileID, a.Type, a.Title, a.ContentLink AS Url, c.ContentInfo as FileID, a.ColumnID, a.PublishTime, GROUP_CONCAT(t.CelebrityID) AS Tags FROM cms_articles a
                LEFT JOIN cms_article_celebrity t ON a.ArticleID = t.ArticleID
                LEFT JOIN cms_article_content c ON a.ArticleID = c.ArticleID
                WHERE ( CASE a.Type WHEN 4 THEN c.Type = 4 WHEN 2 THEN c.Type = 0 WHEN 5 THEN c.Type = 0 ELSE c.Type = 6 END )
                AND ( a.Flag = 0 AND a.PublishStatus = 1 )
                AND a.Type IN ( 1,2,5,101,102,103,104,105,106)
                AND a.PublishTime <= NOW() ';

            $sql .= ' and t.CelebrityID in(' . implode(',', $celebrityIds) . ')';
            if ($lastTime) {
                $sql .= ' AND a.PublishTime < "' . date('Y-m-d H:i:s', (int)$lastTime) . '" ';
            }
            $sql .= ' GROUP BY a.ArticleID ORDER BY a.PublishTime DESC LIMIT ' . $limit;
            $result = $this->query($sql);
            while ($row = $result->fetch_assoc()) {
                $list[] = $row;
            }
        } else {
            $endSql = '';
            if ($tagIds) {
                $endSql .= ' t.TagId in(' . implode(',', $tagIds) . ')';
            }
            if ($columnsId) {
                if ($endSql) {
                    $endSql .= ' or a.ColumnID in(' . implode(',', $columnsId) . ')';
                } else {
                    $endSql .= ' a.ColumnID in(' . implode(',', $columnsId) . ')';
                }

            }
            $sql = 'SELECT a.ArticleID, c.ID AS ContentID,c.ContentInfo as FileID, a.Type, a.Title, a.ContentLink AS Url, c.ContentInfo as FileID, a.ColumnID, a.PublishTime, GROUP_CONCAT(t.TagID) AS Tags FROM cms_articles a
                LEFT JOIN cms_article_tags t ON a.ArticleID = t.ArticleID
                LEFT JOIN cms_article_content c ON a.ArticleID = c.ArticleID
                WHERE ( CASE a.Type WHEN 4 THEN c.Type = 4 WHEN 2 THEN c.Type = 0 WHEN 5 THEN c.Type = 0 ELSE c.Type = 6 END )
                AND ( a.Flag = 0 AND a.PublishStatus = 1 )
                AND a.Type IN ( 1,2,4,5,101,102,103,104,105,106)
                AND a.PublishTime <= NOW() AND t.Flag = 0 ';

            if ($endSql) {
                $sql .= ' and (' . $endSql . ')';
            }
            if ($lastTime) {
                $sql .= ' AND a.PublishTime < "' . date('Y-m-d H:i:s', (int)$lastTime) . '" ';
            }
            $sql .= ' GROUP BY a.ArticleID ORDER BY a.PublishTime DESC LIMIT ' . $limit;
            $result = $this->query($sql);
            while ($row = $result->fetch_assoc()) {
                $list[] = $row;
            }
        }

        if ($list) {
            $list = \haibao\jiepai\data\BaseMysql::mergeDataAndImage($list, 'FileID');
        }

        return $list;
    }

    public function getColumnsList($columnsIds)
    {
        $list = array();
        $sql = 'SELECT ColumnID,ColumnName FROM cms_columns where ColumnID in (' . implode(',', $columnsIds) . ') AND Flag=0';
        $result = $this->query($sql);
        while ($row = $result->fetch_assoc()) {
            $list[$row['ColumnID']] = $row['ColumnName'];
        }

        return $list;
    }

    /**
     * 获取nickname
     */
    public function getUsersByIds($userIds)
    {
        $str = preg_replace('/(\d+)/', '%s', implode(',', $userIds));
        $sql = "SELECT * from cms_users where UserID in (" . $str . ")";
        $result = $this->query($sql, $userIds);
        $returnUserName = array();
        while ($row = $result->fetch_assoc()) {
            $returnUserName[$row['UserID']] = $row;

        }
        return $returnUserName;
    }


    public function getUserActionsListByType($articleType, $userId, $cursor = null)
    {
        $sql = 'select DISTINCT TypeID,ID from cms_user_action where Flag = 0 AND Type=%s and UserID=%s';

        if ($cursor) $sql .= " AND ID < " . $cursor;

        $sql .= ' ORDER BY ID DESC LIMIT ' . \haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LARGE_ARTICLE_PAGE_SIZE);
        return $this->normalQuery($sql, array($articleType, $userId));
    }

    public function getAlbumIDByContentID($userId, $contentIdList)
    {
        $str = preg_replace('/(\d+)/', '%s', implode(',', $contentIdList));
        $result = $this->query('SELECT DISTINCT AlbumID From cms_album_pictures WHERE ContentID in (' . $str . ') AND Flag = 0 AND UserID=' . $userId, $contentIdList);
        $albumList = array();
        while ($result->fetch_assoc()) {
            array_push($albumList, $result->getData('AlbumID'));
        }
        return $albumList;
    }

    /**
     * 取消收藏图片
     */
    public function cancelCollectPictureToAlbum($userId, array $contentIdList, $albumId = null)
    {
        $count = 0;
        $albumIdList = $this->getAlbumIDByContentID($userId, $contentIdList);
        $str = preg_replace('/(\d+)/', '%s', implode(',', $contentIdList));
        $sql = 'UPDATE cms_album_pictures SET Flag = -1 WHERE Flag = 0 AND Type=1 AND ContentID in (' . $str . ') AND UserID=%s';
        if($albumId){
            $sql .= ' AND AlbumID='.$albumId;
        }
        $param = $contentIdList;
        array_push($param, $userId);
        $this->query($sql, $param);

        // $this->deleteAlbumCache($userId);
        if ($albumIdList) {
            $albumId = $albumIdList[0];
            $count = $this->getAlbumPictureNum($albumId, $userId);
        }
        return $count;
    }

    /**
     * 收藏图片到相册
     */
    public function CollectPictureToAlbum($userId, array $contentIds, $albumId)
    {
        $articleIdArr = $this->getArticleFileFromContentID($contentIds);
        if ($contentIds && $articleIdArr) {
            foreach ($contentIds as $key => $value) {
                $sql = 'INSERT INTO cms_album_pictures (ContentID,AlbumID,UserID,ArticleID,FileID) select ';
                $sql .= $value . ',' . $albumId . ',' . $userId . ',' . (isset($articleIdArr[$value]) ? $articleIdArr[$value]['ArticleID'] : '') . ',' . (isset($articleIdArr[$value]) ? $articleIdArr[$value]['FileID'] : '');
                $sql .= ' from DUAL WHERE NOT EXISTS(SELECT * from cms_album_pictures where ContentID=' . $value . ' AND AlbumID=' . $albumId;
                $sql .= ' AND Flag = 0 AND UserID = ' . $userId . ')';
                $this->query($sql);
            }
        }
        //$this->deleteAlbumCache($userId);
    }

    /**
     * 通过ContentID获取FileID和ArticleID
     */
    public function getArticleFileFromContentID($contentIds)
    {
        $str = preg_replace('/(\d+)/', '%s', implode(',', $contentIds));
        $result = $this->query('SELECT ID,ArticleID,ContentInfo as FileID FROM cms_article_content WHERE ID in(' . $str . ')', $contentIds);
        $retArr = array();
        while ($row = $result->fetch_assoc()) {
            $retArr[$result->getData('ID')] = $row;
        }
        return $retArr;
    }

    /**
     * 查询相册内图片数量
     */
    public function getAlbumPictureNum($albumId, $userId)
    {
        $sql = 'SELECT count(*) as count from cms_album_pictures where UserID=%s and AlbumID=%s and Flag=0';
        $result = $this->query($sql, array($userId, $albumId))->fetch_assoc();
        return isset($result['count']) ? $result['count'] : 0;
    }

    /**
     * 删除相册缓存
     * @param $userId
     */
    public function deleteAlbumCache($userId)
    {
        // 清除缓存，等待下次取的适合更新缓存内容
        $cache = new \haibao\jiepai\cache\Album();
        $cache->deleteAlbumList($userId);
        $cache->deleteAlbumInfo($userId);
    }

    /**
     * 保存街拍用户
     */
    public function saveCmsUser($model)
    {
        $this->add($model);
    }

    /**
     * 首次进入消息
     */
    public function firstLoginMessage($userId)
    {

    }
}